/*
* Copyright 2017 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-service-maintenanceorder
*
* @File name : MaintenanceorderService.java
*
* @Author : Administrator
*
* @Date : 2017年3月7日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2017年3月7日    Administrator    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/

package com.yonyou.gmmc.service.maintenanceorder.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.marketing.common.dto.customerInfo.CarInfoDto;
import org.marketing.common.dto.maintenanceorder.MaintenanceDto;
import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.util.CheckUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yonyou.gmmc.service.maintenanceorder.dao.TtEvaluationResultDetailMapper;
import com.yonyou.gmmc.service.maintenanceorder.dao.TtEvaluationResultMapper;
import com.yonyou.gmmc.service.maintenanceorder.dao.TtMaintenanceRecordMapper;
import com.yonyou.gmmc.service.maintenanceorder.entity.EvaluationResultDetailPO;
import com.yonyou.gmmc.service.maintenanceorder.entity.EvaluationResultPO;
import com.yonyou.gmmc.service.maintenanceorder.model.TtEvaluationResult;
import com.yonyou.gmmc.service.maintenanceorder.model.TtEvaluationResultDetail;

/**
 *
 * @author Administrator TODO description
 * @date 2017年3月7日
 */
@Transactional
@Service("maintenanceorderService")
public class MaintenanceorderService {

	private Logger logger = Logger.getLogger(this.getClass());

	@Autowired
	private TtMaintenanceRecordMapper ttMaintenanceRecordMapper;
	@Autowired
	private TtEvaluationResultMapper ttEvaluationResultMapper;
	@Autowired
	private TtEvaluationResultDetailMapper ttEvaluationResultDetailMapper;

	/**
	 * 维修履历列表查询
	 * 
	 * @author QianKun
	 * @date 2017年3月7日
	 * @param vin
	 * @return
	 */
	public Map<String, Object> getMaintenance(String userId, String pvin) {
		Map<String, Object> map = new HashMap<String, Object>();
		;
		List<MaintenanceDto> dtoList = null;
		List<CarInfoDto> carList = null;
		String vin = "";
		carList = ttMaintenanceRecordMapper.queryCarInfo(Integer.valueOf(userId));
		if (carList == null || carList.size() == 0) {
			map.put("carInfo", new ArrayList<CarInfoDto>());
		} else {
			// vin不为空，获取当前车辆的履历，为空获取车辆列表中第一辆车的履历
			if (CheckUtil.NullOrEmpty(pvin)) {
				vin = carList.get(0).getVin();
			} else {
				vin = pvin;
			}
			map.put("carInfo", carList);
			dtoList = ttMaintenanceRecordMapper.queryMaintenanceMap(vin);
			if (dtoList == null || dtoList.size() == 0) {
				map.put("maintenenceOrder", new ArrayList<MaintenanceDto>());
			} else {
				Integer evaluationId = ttMaintenanceRecordMapper.queryEvaluationId();
				for (MaintenanceDto maintenanceDto : dtoList) {
					if (maintenanceDto.getMaintenanceWorkOrderNum() != null) {
						Integer ifEvaluation = checkEvaluation(userId,
								maintenanceDto.getMaintenanceWorkOrderNum() + maintenanceDto.getDealerCode(),
								evaluationId);
						maintenanceDto.setIfEvaluation(ifEvaluation);
					}
				}
				map.put("maintenenceOrder", dtoList);
			}
		}
		return map;
	}

	/**
	 * 维修履历详情查询
	 * 
	 * @author
	 * @date 2017年3月7日
	 * @param maintenanceWorkOrderNum
	 * @return
	 */
	public List<MaintenanceDto> getMaintenanceById(String maintenanceWorkOrderNum, String dealerCode) {
		List<MaintenanceDto> dtoList = new ArrayList<>();
		dtoList = ttMaintenanceRecordMapper.queryMaintenanceByIdMap(maintenanceWorkOrderNum, dealerCode);
		return dtoList;
	}

	/**
	 * 判断是否存在评价工单
	 * 
	 * @return
	 */
	private Integer checkEvaluation(String userId, String workOrderNumber, Integer evaluationId) {
		TtEvaluationResult eva = new TtEvaluationResult();
		eva.setOrderNumber(workOrderNumber);
		eva.setEvaluationId(evaluationId);
		eva.setCarOwnerId(Integer.valueOf(userId));
		TtEvaluationResult list = ttEvaluationResultMapper.selectOne(eva);
		if (list == null) {
			logger.info("工单未评价！");
			return 0;
		} else if (list.getIfEvaluate() == 0) {
			logger.info("工单未评价！");
			return 0;
		} else {
			logger.info("工单已评价！");
			return 1;
		}
	}

	/**
	 * 查看工单评价
	 * 
	 * @param type
	 * @param orderNumber
	 * @param openId
	 * @return
	 */
	public EvaluationResultPO addEvaluation(Integer type, String orderNumber, String userId, Integer evaType) {
		logger.info("通过openId查询的userId为：" + userId);
		EvaluationResultPO reslut = ttMaintenanceRecordMapper.addEvaluation(type, orderNumber, Integer.valueOf(userId),
				evaType);
		return reslut;
	}

	/**
	 * 提交工单评价
	 * 
	 * @param evaluationResultPO
	 * @param openId
	 * @return
	 */
	public Map<String, Object> saveEvaluation(EvaluationResultPO evaluationResultPO, String userId) {
		try {
			Map<String, Object> result = new HashMap<>();
			String userPhone = ttMaintenanceRecordMapper.queryUserPhone(Integer.valueOf(userId));
			logger.info("通过userId查询的手机号码PHONE为：" + userPhone);

			TtEvaluationResult ttEvaluationResult = new TtEvaluationResult();
			Integer resultId = ttMaintenanceRecordMapper.queryResultId();
			ttEvaluationResult.setResultId(resultId);
			ttEvaluationResult.setCarOwnerId(Integer.valueOf(userId));
			ttEvaluationResult.setPhone(Long.valueOf(userPhone));
			ttEvaluationResult.setEvaluationContent(evaluationResultPO.getEvaluationContent());
			ttEvaluationResult.setOrderNumber(evaluationResultPO.getOrderNumber());
			ttEvaluationResult.setEvaluationId(evaluationResultPO.getEvaluationId());
			ttEvaluationResult.setCreateDate(new Date());
			ttEvaluationResult.setIfEvaluate(1);
			ttEvaluationResultMapper.insertSelective(ttEvaluationResult);
			logger.info("工单评价result表成功");

			List<EvaluationResultDetailPO> evaluationList = evaluationResultPO.getEvaluationResultDetailPO();
			if (evaluationList != null) {
				for (EvaluationResultDetailPO evaluationPO : evaluationList) {
					TtEvaluationResultDetail ttEvaluationResultDetail = new TtEvaluationResultDetail();
					ttEvaluationResultDetail.setResultId(resultId);
					ttEvaluationResultDetail.setEvaluationDetailId(evaluationPO.getDetailId());
					ttEvaluationResultDetail.setStarSum(evaluationPO.getStarSum());
					ttEvaluationResultDetailMapper.insertSelective(ttEvaluationResultDetail);
					logger.info("工单评价明细 表插入成功！");
				}
			}

			result.put("flag", 1);
			result.put("msg", "提交工单评价成功！");
			// 发放卡券
			// logger.info("查询该用户潜客ID");
			// Integer potentialUserId =
			// tmPotentialUserMapper.queryPotentialId(openId);
			// logger.info("潜客ID为：" + potentialUserId);
			// String dealerCode =
			// tmPotentialUserMapper.selectDealerById(potentialUserId);
			// logger.info("自动发放卡券");
			// SendTicket ticketDto = new SendTicket();
			// ticketDto.setBizCode(1004);
			// ticketDto.setTriggerCode(10041001);
			// ticketDto.setUserId(potentialUserId);
			// if (dealerCode != null) {
			// ticketDto.setDealerCode(dealerCode);
			// } else {
			// ticketDto.setDealerCode("");
			// }
			// ticketDto.setBatchId("");
			// ticketDto.setBizId(resultId.toString());
			// BizEvent et = new BizEvent();
			// et.setEventBizType(EventBizType.SEND_TICKET);
			// et.setEventBizStep(EventBizStep.SEND_TICKTE_TO_USER);
			// et.setEventKey("TICKET:" + ticketDto.getUserId() + ":" + new
			// Date().getTime());
			// et.setEventData(MapConverUtil.PO2Map(ticketDto));
			// String s = eventService.sendEvent2MQ(et);
			// logger.info("发放卡券MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);
			// logger.info("提交工单评价成功！");

			// 发放积分

			// logger.info("提交工单评价完成，发积分_Start");
			// EventCommitEvaluationDTO ecDto = new EventCommitEvaluationDTO();
			// ecDto.setUserId(userId);
			// logger.info("USER_ID为：" + userId);
			// ecDto.setPhone(userPhone);
			// logger.info("PHONE为：" + userPhone);
			// ecDto.setWorkOrderNo(workOrderNo);
			// logger.info("workOrderNo为：" + workOrderNo);
			// BizEvent event = new BizEvent();
			// event.setEventKey("EVAL" + "-" + ecDto.getUserId() + "-" +
			// ecDto.getWorkOrderNo());
			// event.setEventBizType(EventBizType.EVALUATION);
			// event.setEventBizStep(EventBizStep.EVALUATION_SEND_POINTS);
			// event.setEventData(MapConverUtil.PO2Map(ecDto));
			// eventService.sendEvent2MQ(event);
			// logger.info("提交工单评价完成发积分_End");

			return result;
		} catch (Exception e) {
			logger.error("异常：" + e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	/**
	 * 校验是否存在可评价工单
	 * 
	 * @param type
	 * @param orderNumber
	 * @param openId
	 * @return
	 */
	public Map<String, Object> checkEvaluation(Integer type, String orderNumber, String userId) {
		Map<String, Object> result = new HashMap<>();
		Integer evaluationId = ttMaintenanceRecordMapper.queryEvaluationId();
		TtEvaluationResult record = new TtEvaluationResult();
		record.setCarOwnerId(Integer.valueOf(userId));
		record.setOrderNumber(orderNumber);
		record.setEvaluationId(evaluationId);
		record = ttEvaluationResultMapper.selectOne(record);
		if (record == null) {
			result.put("ifEvaluate", 0);
			result.put("msg", "工单未评价！");
			logger.info("工单未评价！");
		} else {
			Integer ifEvaluate = record.getIfEvaluate();
			if (ifEvaluate == 0) {
				result.put("ifEvaluate", 0);
				result.put("msg", "工单未评价！");
				logger.info("工单未评价！");
			} else {
				result.put("ifEvaluate", 1);
				result.put("msg", "工单已评价！");
				logger.info("工单已评价！");
			}
		}
		logger.info("校验是否存在可评价工单完成！");
		return result;
	}
}
